package com.springengine.udpchat;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity {

    DatagramSocket mUDPSocket;
    DatagramSocket mUDPServer;
    TextView mChatBoard;
    EditText mChatInput;
    EditText mTargetAddress;
    TextView mLocalIP;
    private Handler mUpdateUIHandler;
    private Handler mSocketSendDoneHandler;
    static final int charPort = 12345;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        WifiManager manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
//        WifiManager.MulticastLock lock= manager.createMulticastLock("test wifi");
//        lock.acquire();
        mChatBoard = (TextView) findViewById(R.id.id_char_board);
        mChatInput = (EditText) findViewById(R.id.id_chat_input);
        mTargetAddress = (EditText)findViewById(R.id.id_address);

        mChatBoard.setMovementMethod(ScrollingMovementMethod.getInstance());

        mLocalIP = (TextView)findViewById(R.id.id_local_ip);
        String localIP = getHostIP();
        mLocalIP.setText(localIP);

        new Thread(mSocketInit).start();
        mUpdateUIHandler = new Handler() {
            @Override
            public void handleMessage(Message m) {
                super.handleMessage(m);
                Bundle b =m.getData();
                byte[] recvBytes = b.getByteArray("recv_string");
                int recvLen = b.getInt("recv_len");
                String recvString = new String(recvBytes, 0, recvLen);
                mChatBoard.setText(mChatBoard.getText().toString() + '\n' + recvString);
            }
        };

        mSocketSendDoneHandler = new Handler() {
            @Override
            public  void  handleMessage(Message m) {
                super.handleMessage(m);
                mChatInput.setText("");
            }
        };

    }

    public void onSendButtonClick(View v) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    InetAddress addr = InetAddress.getByName(mTargetAddress.getText().toString());
                    String sendString = mChatInput.getText().toString();
                    mUDPSocket.send(new DatagramPacket(sendString.getBytes(), sendString.getBytes().length, addr, charPort));
                    mSocketSendDoneHandler.sendMessage(new Message());
                }catch (UnknownHostException e){
                    //unknow host
                }catch (IOException e) {

                }
            }
        }).start();

    }



    Runnable mSocketInit = new Runnable() {
        @Override
        public void run(){
            try {
                mUDPSocket = new DatagramSocket();
                mUDPServer = new DatagramSocket(charPort);

                while (true) {
                    byte[] b = new byte[1500];
                    Arrays.fill(b, (byte) 0);

                    DatagramPacket recvPacket = new DatagramPacket(b, 1500);
                    mUDPServer.receive(recvPacket);
                    Bundle bundle = new Bundle();
                    bundle.putByteArray("recv_string", recvPacket.getData());
                    bundle.putInt("recv_len", recvPacket.getLength());
                    Message mes = new Message();
                    mes.setData(bundle);
                    mUpdateUIHandler.sendMessage(mes);
                    Thread.sleep(100);
                }
            }catch (IOException e){

            }catch (InterruptedException e) {

            }
        }
    };

    static String getHostIP() {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            Log.i("yao", "SocketException");
            e.printStackTrace();
        }
        return hostIp;
    }
}
